package com.minis.beans.factory.support;

import com.minis.BeansException;
import com.minis.beans.factory.config.BeanPostProcessor;

import java.util.ArrayList;
import java.util.List;

/**
 * 功能描述
 *
 * @author wanghongqian
 * @date 2023/10/18 19:09
 */
public abstract class AbstractAutowireCapableBeanFactory
        extends AbstractBeanFactory implements AutowireCapableBeanFactory{
    private final List<BeanPostProcessor> beanPostProcessors = new ArrayList<>();
    @Override
    public void addBeanPostProcessor(BeanPostProcessor beanPostProcessor) {
        this.beanPostProcessors.remove(beanPostProcessor);
        this.beanPostProcessors.add(beanPostProcessor);
    }

    @Override
    public int getBeanPostProcessorCount() {
        return beanPostProcessors.size();
    }

    public List<BeanPostProcessor> getBeanPostProcessors(){
        return this.beanPostProcessors;
    }

    @Override
    public Object applyBeanPostProcessorBeforeInitialization(Object existingBean, String beanName) throws BeansException {
        Object result = existingBean;
        for(BeanPostProcessor beanPostProcessor:getBeanPostProcessors()){
            beanPostProcessor.setBeanFactory(this);
            result =  beanPostProcessor.postProcessBeforeInitialization(result,beanName);
            if(result == null){
                return result;
            }
        }
        return result;
    }

    @Override
    public Object applyBeanPostProcessorAfterInitialization(Object existingBean, String beanName) throws BeansException {
        Object result = existingBean;
        for(BeanPostProcessor beanPostProcessor:getBeanPostProcessors()){
            beanPostProcessor.setBeanFactory(this);
            result = beanPostProcessor.postProcessAfterInitialization(result,beanName);
            if(result == null){
                return result;
            }
        }
        return result;
    }
}
